package sicnu.cs.aps.service.impl;

import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import sicnu.cs.aps.common.util.RequestUtil;
import sicnu.cs.aps.domain.entity.Role;
import sicnu.cs.aps.mapper.*;
import sicnu.cs.aps.service.IUserInfoService;

import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.stream.Collectors;

import static sicnu.cs.aps.common.Constants.*;

/**
 * @author CaiKe
 * @date 2022/5/27 11:46
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserInfoServiceImpl implements IUserInfoService {

    private final UserInfoMapper userInfoMapper;
    private final StudentInfoMapper studentInfoMapper;
    private final TeacherInfoMapper teacherInfoMapper;
    private final CollegeInfoMapper collegeInfoMapper;
    private final RoleMapper roleMapper;
    private Gson gson = new Gson();

    /**
     * 目标用户是否属于目标学院
     *
     * @param userId    目标用户Id
     * @param collegeId 目标学院Id
     * @return true&false
     */
    @Override
    public boolean isUserInCollege(Long userId, Long collegeId) {
        return userInfoMapper.countByUserIdAndCollegeId(userId, collegeId) > 0;
    }

    /**
     * 获取当前用户信息json
     *
     * @return json
     */
    @Override
    public String getCurrentJSONedUserInfo() {
        final Set<String> roles = RequestUtil.getCurrentUserRole();
        Long id = RequestUtil.getCurrentUserId();
        return getString(id, roles);
    }

    /**
     * 通过id获取用户的角色信息
     *
     * @param id id
     * @return 角色信息
     */
    @Override
    public String getJSONedUserInfoById(Long id) {
        Set<String> roles = null;
        roles = roleMapper.findRolesByUserid(id).stream().map(Role::getAuthority).collect(Collectors.toSet());
        return getString(id, roles);
    }

    private String getString(Long id, Set<String> roles) {
        if (roles.contains(ROLE_STUDENT)) {
            return gson.toJson(studentInfoMapper.selectById(id));
        } else {
            if (roles.contains(ROLE_TEACHER)) {
                return gson.toJson(teacherInfoMapper.selectById(id));
            } else if (roles.contains(ROLE_COLLEGE)) {
                return gson.toJson(collegeInfoMapper.selectById(id));
            } else if (roles.contains(ROLE_COLLEGE_SUB)) {
                return gson.toJson(collegeInfoMapper.selectCollegeInfoBySubId(id));
            } else if (RequestUtil.isCurrentUserAUniversity()) {
                return gson.toJson(Map.of("name", "四川师范大学"));
            } else if (roles.contains(ROLE_SYSTEM)) {
                return gson.toJson(Map.of("name", "管理人员"));
            } else {
                throw new NoSuchElementException("No Identity!");
            }
        }
    }

    @Override
    public Long selectCollegeIdByUserId(Long userId) {
        return studentInfoMapper.selectCollegeIdByUserId(userId);
    }
}